package cz.proks.schoolpupilbook.gae.converter;

import java.util.LinkedList;
import java.util.List;

import com.google.appengine.api.datastore.KeyFactory;

import cz.proks.schoolpupilbook.gae.dao.CourseDAO;
import cz.proks.schoolpupilbook.gae.dao.UserDAO;
import cz.proks.schoolpupilbook.gae.dbo.MarkCommentDBO;
import cz.proks.schoolpupilbook.gae.dbo.MarkDBO;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.Mark;
import cz.proks.schoolpupilbook.shared.domain.MarkComment;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.util.Tester;

public class MarkConverter implements Converter<MarkDBO, Mark>{
	@Override
	public MarkDBO getDBO(Mark domain) {
		if (domain == null)
			return null;
		
		MarkDBO dbo = new MarkDBO();
		
		if (!Tester.isEmpty(domain.getId()))
			dbo.setId(KeyFactory.stringToKey(domain.getId()));
		
		List<MarkCommentDBO> dboComments = new LinkedList<MarkCommentDBO>();
		if (domain.getComments() != null)
			for (MarkComment mc : domain.getComments()) {
				MarkCommentDBO mcDBO = new MarkCommentDBO();
				
				if (!Tester.isEmpty(mc.getId()))
					mcDBO.setId(KeyFactory.stringToKey(mc.getId()));
				
				mcDBO.setTime(mc.getTime());
				mcDBO.setMark(dbo);
				mcDBO.setContributorKey(KeyFactory.stringToKey(mc.getContributor().getId()));
				mcDBO.setComment(mc.getComment());
				dboComments.add(mcDBO);
			}
		
		dbo.setTime(domain.getTime());
		dbo.setLectorKey(KeyFactory.stringToKey(domain.getLector().getId()));
		dbo.setCourseKey(KeyFactory.stringToKey(domain.getCourse().getId()));
		dbo.setStudentKey(KeyFactory.stringToKey(domain.getStudent().getId()));
		dbo.setGrade(domain.getMark());
		dbo.setComments(dboComments);
		
		return dbo;
	}

	@Override
	public Mark getDomain(MarkDBO dbo) {
		if (dbo == null)
			return null;
		
		UserDAO userDao = new UserDAO();
		CourseDAO courseDao = new CourseDAO();
		
		User lector = userDao.find(dbo.getLectorKey());
		User student = userDao.find(dbo.getStudentKey());
		Course course = courseDao.find(dbo.getCourseKey());
		
		LinkedList<MarkComment> comments = new LinkedList<MarkComment>();
		Mark domain = new Mark(KeyFactory.keyToString(dbo.getId()), lector, student, course, dbo.getTime(), dbo.getGrade(), comments);
				
		if (dbo.getComments() != null) 
			for(MarkCommentDBO mcDBO : dbo.getComments()) {
				User contributor = userDao.find(mcDBO.getContributorKey());
				MarkComment mc = new MarkComment(KeyFactory.keyToString(mcDBO.getId()), domain, mcDBO.getTime(), contributor, mcDBO.getComment());
				comments.add(mc);
			}
				
		return domain;
	}
}
